package com.ccb.sc.order.vo;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ccb.sc.common.modules.goods.enums.GoodsStatus;
import com.ccb.sc.common.modules.goods.vo.GoodsDetailVo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.util.StringUtils;

import java.beans.Transient;
import java.math.BigDecimal;

/**
 * @author ken
 * @version 1.0
 * @date 2020-09-24
 */
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel
public class ShoppingCartItemVo extends GoodsDetailVo {

    @ApiModelProperty("库存")
    private Integer stock;

    @JsonIgnore
    private GoodsStatus goodsStatus;

    @ApiModelProperty("商品id")
    private Long goodsId;

    @ApiModelProperty("商品规格id")
    private Long goodsSpecsId;

    @ApiModelProperty("商品规格图片")
    private String goodsSpecsPicture;

    @ApiModelProperty("数量")
    private Integer quantity;

    @ApiModelProperty("是否选择")
    private Boolean selected = Boolean.FALSE;

    @ApiModelProperty("是否有效")
    private Boolean isValid = Boolean.FALSE;

    @ApiModelProperty("商品规格")
    private String goodsSpec;

    @ApiModelProperty("sku团购价格")
    private String skuPrice;

    @ApiModelProperty("团购价格")
    private BigDecimal grouponPrice;

    public Boolean getIsValid() {
        this.isValid = stock != null && stock > 0 && goodsStatus == GoodsStatus.ON_SALE;
        return this.isValid;
    }

    public BigDecimal getGrouponPrice() {
        if (StringUtils.hasText(skuPrice) && JSONUtil.isTypeJSON(skuPrice)) {
            JSONObject json = JSON.parseObject(skuPrice);
            return json.getBigDecimal(String.valueOf(getGoodsSpecsId()));
        }
        return null;
    }

    public Boolean isGroupon() {
        return getGrouponPrice()!= null && getGrouponPrice().compareTo(BigDecimal.ZERO) > 0;
    }

    public Boolean getSelected() {
        if (getIsValid()) {
            return selected;
        }
        return false;
    }

    @Transient
    public BigDecimal getSubtotalAmount() {
        if (getSalePrice() != null && getQuantity() != null) {
            return getSalePrice().multiply(new BigDecimal(getQuantity()));
        }
        return BigDecimal.ZERO;
    }

    @Transient
    public BigDecimal getGrouponSubtotalAmount() {
        if (getGrouponPrice() != null && getQuantity() != null) {
            return getGrouponPrice().multiply(new BigDecimal(getQuantity()));
        }
        return BigDecimal.ZERO;
    }

    @Transient
    public Integer getSubtotalExchangePoints() {
        if (getExchangePoints() != null && getQuantity() != null) {
            return getExchangePoints() * getQuantity();
        }
        return 0;
    }

}
